package org.markwebb.mina.playground.hbfilter.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.transport.socket.nio.SocketAcceptor;

public class HbServer {

	public HbServer( int port ) throws IOException{
		IoAcceptor acceptor = new SocketAcceptor();

        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put( Charset.defaultCharset().encode("heartbeat") );
        buffer.flip();
        HeartbeatIdleFilter hbf = new HeartbeatIdleFilter(buffer);
        
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        chain.addLast("heartbeat", hbf);
        chain.addLast("logger", new LoggingFilter() );
        
        // Bind
        acceptor.setLocalAddress( new InetSocketAddress( port ) );
        acceptor.setHandler( new HbHandler() );
        acceptor.bind();

        System.out.println( "Listening on port " + port );
	}
	
	public static void main(String[] args) throws IOException {
		int port = Integer.parseInt( args[0] );
		
		new HbServer( port );
	}
}
